package com.xiaojian.blog.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaojian.blog.constant.WebConstant;
import com.xiaojian.blog.dao.LogPOMapper;
import com.xiaojian.blog.model.LogPO;
import com.xiaojian.blog.model.LogPOExample;
import com.xiaojian.blog.service.LogService;
import com.xiaojian.blog.utils.DateKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
@Service
public class LogServiceImpl implements LogService {
    private Logger LOGGER = LoggerFactory.getLogger(LogServiceImpl.class);

    @Resource
    private LogPOMapper logPOMapper;

    @Override
    public void insertLog(LogPO logPO) {
        logPOMapper.insert(logPO);
    }

    @Override
    public void insertLog(String action, String data, String ip, Integer authorId) {
        LogPO logPO = new LogPO();
        logPO.setAction(action);
        logPO.setData(data);
        logPO.setIp(ip);
        logPO.setAuthorId(authorId);
        logPO.setCreated(DateKit.getCurrentUnixTime());
        logPOMapper.insert(logPO);
    }

    @Override
    public List<LogPO> getLogs(int page, int limit) {
        LOGGER.debug("Enter getLogs method:page={},limit={}", page, limit);
        if (page <= 0) {
            page = 1;
        }
        if (limit < 1 || limit > WebConstant.MAX_POSTS) {
            limit = 10;
        }
        LogPOExample logPOExample = new LogPOExample();
        logPOExample.setOrderByClause("id desc");
        PageHelper.startPage((page - 1) * limit, limit);
        List<LogPO> logPOS = logPOMapper.selectByExample(logPOExample);
        LOGGER.debug("Exit getLogs method");
        return logPOS;
    }
}
